import React, { useState } from 'react';
import { FileItem, FolderItem } from '../types';
import { getFileIcon, formatFileSize } from '../utils/fileUtils';

interface FileListProps {
    folders: FolderItem[];
    files: FileItem[];
    loading: boolean;
    selectedItems: Set<string>;
    onSelectItem: (type: 'file' | 'folder', name: string) => void;
    onNavigateToFolder: (folderName: string) => void;
    disabled?: boolean;
}

const FileList: React.FC<FileListProps> = ({
    folders,
    files,
    loading,
    selectedItems,
    onSelectItem,
    onNavigateToFolder,
    disabled = false
}) => {
    if (loading) {
        return (
            <div className="text-center py-10">
                <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mb-4"></div>
                <div className="text-gray-600">正在加载文件列表...</div>
            </div>
        );
    }

    if (folders.length === 0 && files.length === 0) {
        return (
            <div className="text-center py-10">
                <div className="text-gray-600">📂 文件夹为空</div>
            </div>
        );
    }

    const handleItemClick = (type: 'file' | 'folder', name: string) => {
        if (disabled) return;
        onSelectItem(type, name);
    };

    const handleFolderDoubleClick = (folderName: string) => {
        if (disabled) return;
        onNavigateToFolder(folderName);
    };

    const isSelected = (type: 'file' | 'folder', name: string) => {
        return selectedItems.has(`${type}:${name}`);
    };

    // 图片预览组件
    const ImagePreview: React.FC<{ file: FileItem }> = ({ file }) => {
        const [imageError, setImageError] = useState(false);
        const [imageLoading, setImageLoading] = useState(true);

        const handleImageLoad = () => {
            setImageLoading(false);
        };

        const handleImageError = () => {
            setImageError(true);
            setImageLoading(false);
        };

        if (file.type !== 'image' || imageError) {
            return (
                <div className="relative w-full h-36 mb-2 flex items-center justify-center bg-gray-100 rounded">
                    <div className="text-5xl">{getFileIcon(file.type)}</div>
                </div>
            );
        }

        return (
            <div className="relative w-full h-60 mb-2 bg-gray-100 rounded overflow-hidden" >
                {imageLoading && (
                    <div className="absolute inset-0 flex items-center justify-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
                    </div>
                )}
                <img
                    src={file.customUrl}
                    alt={file.fileName}
                    className={`w-full h-full object-contain transition-opacity duration-200 ${imageLoading ? 'opacity-0' : 'opacity-100'}`}
                    onLoad={handleImageLoad}
                    onError={handleImageError}
                    loading="lazy"
                />
            </div>
        );
    };

    return (
        <div className={`grid grid-cols-1 sm:grid-cols-2 md:grid-cols-5 lg:grid-cols-6 gap-6 mt-5 ${disabled ? 'opacity-50 pointer-events-none' : ''}`}>
            {/* 渲染文件夹 */}
            {folders.map((folder) => (
                <div
                    key={folder.name}
                    className={`border-2 rounded-lg p-4 text-center cursor-pointer transition-all hover:shadow-md hover:-translate-y-0.5 ${isSelected('folder', folder.name)
                            ? 'border-orange-400 bg-orange-50'
                            : 'border-transparent bg-yellow-50 hover:border-yellow-200'
                        } ${disabled ? 'cursor-not-allowed' : ''}`}
                    onClick={() => handleItemClick('folder', folder.name)}
                    onDoubleClick={() => handleFolderDoubleClick(folder.name)}
                >
                    <div className="text-4xl mb-2">📁</div>
                    <div className="font-medium text-sm break-all">{folder.displayName}</div>
                    <div className="text-xs text-gray-500 mt-1">文件夹</div>
                </div>
            ))}

            {/* 渲染文件 */}
            {files.map((file) => (
                <div
                    key={file.name}
                    className={`border-2 rounded-lg p-4 text-center cursor-pointer transition-all hover:shadow-md hover:-translate-y-0.5 ${isSelected('file', file.name)
                            ? 'border-blue-400 bg-blue-50'
                            : 'border-transparent bg-gray-50 hover:border-gray-200'
                        } ${disabled ? 'cursor-not-allowed' : ''}`}
                    onClick={() => handleItemClick('file', file.name)}
                >
                    <ImagePreview file={file} />
                    <div className="font-medium text-sm break-all mb-1">{file.fileName}</div>
                    <div className="text-xs text-gray-500 mb-2">
                        {file.type} • {formatFileSize(file.size)}
                    </div>
                    <div className="mt-2 p-2 bg-gray-100 rounded text-xs">
                        <a
                            href={file.customUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-blue-600 hover:underline"
                            onClick={(e) => e.stopPropagation()}
                        >
                            查看文件
                        </a>
                        <div className="mt-1 text-gray-500 break-all text-xs">
                            {file.customUrl}
                        </div>
                    </div>
                </div>
            ))}
        </div>
    );
};

export default FileList; 